<template>
  <ul class="list">
    <li v-for="item of letters"
        :key="item"
        :ref="elem => elems[item] = elem"
        class="item"
        @click="handleLetterClick"
        @touchend="handleTouchEnd"
        @touchmove="handleTouchMove"
        @touchstart.prevent="handleTouchStart"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
import {computed, onUpdated, ref} from "vue";

export default {
  name: 'CityAlphabet',
  props: {
    cities: Object,
    l: String
  },
  setup(props, context) {
    let touchStatus = false
    let startY = 0
    let timer = null
    const elems = ref([])
    const letters = computed(() => {
      const letters = []
      for (let i in props.cities) {
        letters.push(i)
      }
      return letters
    })
    onUpdated(() => {
      startY = elems.value['A'].offsetTop
    })

    function handleLetterClick(e) {
      context.emit('change', e.target.innerText)
      // console.log(e.target.innerText)
    }

    function handleTouchStart() {
      touchStatus = true
    }

    function handleTouchEnd() {
      touchStatus = false
    }

    function handleTouchMove(e) {
      if (touchStatus) {
        // console.log(this.l)
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 109

          const index = Math.floor((touchY - startY) / 20)
          // console.log(letters.value[index])
          if (index >= 0 && index < letters.value.length) {
            // for (const i in this.letters) {
            //   letters[i].
            // }
            context.emit('change', letters.value[index])
          }
        }, 8)
      }
    }

    return {elems, letters, handleLetterClick, handleTouchStart, handleTouchEnd, handleTouchMove}
  }
}
</script>

<style lang="stylus" scoped>
@import "~styles/vaibles.styl"
.list
  display flex
  flex-direction column
  justify-content center
  position absolute
  top 2.1rem
  bottom 0
  width .4rem
  right 0

  .item
    line-height .4rem
    text-align center
    font-weight bold
    color $bgColor

.choose
  color red
</style>
